<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>408考研助手</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .control-group {
            margin-bottom: 20px;
            background: #f5f5f5;
            padding: 15px;
            border-radius: 8px;
        }

        select,
        button {
            padding: 8px 12px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            background: #4CAF50;
            color: white;
            cursor: pointer;
        }

        button:disabled {
            background: #cccccc;
        }

        #chatLog {
            height: 400px;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 20px 0;
            overflow-y: auto;
        }

        .message {
            margin: 10px 0;
            padding: 8px;
            border-radius: 4px;
        }

        .user {
            background: #e3f2fd;
        }

        .assistant {
            background: #f0f4c3;
        }

        .system {
            background: #ffcdd2;
            font-size: 0.9em;
        }

        input[type="file"] {
            margin-top: 10px;
        }

        #inputArea {
            display: none;
        }

        /* 初始隐藏输入区域 */
    </style>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/highlight.min.js"></script>
</head>

<body>
    <div class="control-group">
        <select id="modeSelect">
            <option value=0>普通对话</option>
            <option value=1>语音对话模式</option>
            <option value=2>解题模式</option>
            <option value=3>出题模式</option>
        </select>
        <button onclick="initConversation()">初始化对话</button>
        <input type="file" id="fileInput" accept=".json" onchange="loadFromFile(this.files[0])">
    </div>

    <div id="chatLog"></div>

    <div id="inputArea">
        <input type="text" id="userInput" placeholder="输入你的问题..." style="width: 70%">
        <button onclick="sendMessage()">发送</button>
        <div id="cidDisplay" style="margin-top: 10px; color: #666;"></div>
    </div>

    <script>
        let currentCid = null;
        const API_BASE = 'http://localhost:5000';
        // 初始化新对话
        async function initConversation() {
            const mode = document.getElementById('modeSelect').value;

            try {
                const response = await fetch('http://localhost:5000/load', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        messages: [],
                        mode: mode
                    })
                });

                const data = await response.json();
                if (data.error) throw new Error(data.error);

                currentCid = data.dialogId;
                updateUIStatus();
                saveToLocal();
                alert(`已创建新对话 (CID: ${currentCid})`);
            } catch (error) {
                alert('初始化失败: ' + error.message);
            }
        }

        // 发送用户消息
        async function sendMessage() {
            const input = document.getElementById('userInput');
            const message = input.value.trim();
            if (!message) return;

            input.disabled = true;
            appendMessage('user', message);

            try {
                const response = await fetch(API_BASE + '/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        message: message,
                        dialogId: currentCid,
                        stream: false
                    })
                });

                // 检查HTTP状态码
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`请求失败: ${response.status} - ${errorText}`);
                }

                // 解析JSON数据
                const data = await response.json();

                // 提取响应内容
                if (data && data.response) {
                    appendMessage('assistant', data.response);
                } else {
                    throw new Error("无效的响应格式");
                }

                saveToLocal();
            } catch (error) {
                appendMessage('system', '错误: ' + error.message);
            } finally {
                input.disabled = false;
                input.value = '';
            }
        }

        // 本地存储操作
        function saveToLocal() {
            if (!currentCid) return;
            const data = {
                cid: currentCid,
                messages: [...document.querySelectorAll('.message')].map(el => ({
                    role: el.classList.contains('user') ? 'user' :
                        el.classList.contains('assistant') ? 'assistant' : 'system',
                    content: el.textContent.trim()
                }))
            };
            localStorage.setItem(currentCid, JSON.stringify(data));
        }

        // 从文件加载对话
        async function loadFromFile(file) {
            const reader = new FileReader();
            reader.onload = async (e) => {
                try {
                    const data = JSON.parse(e.target.result);

                    const response = await fetch('http://localhost:5000/load', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            messages: data.messages,
                            mode: '无预设'
                        })
                    });

                    const resData = await response.json();
                    currentCid = resData.dialogId;
                    updateUIStatus();
                    data.messages.forEach(msg => appendMessage(msg.role, msg.content));
                    saveToLocal();
                } catch (error) {
                    alert('文件加载失败: ' + error.message);
                }
            };
            reader.readAsText(file);
        }

        // 界面更新函数
        function updateUIStatus() {
            document.getElementById('inputArea').style.display = 'block';
            document.getElementById('cidDisplay').textContent = `当前会话ID: ${currentCid}`;
        }

        function appendMessage(role, content) {
            const log = document.getElementById('chatLog');
            const div = document.createElement('div');
            div.className = `message ${role}`;

            // 添加带格式的内容显示
            div.innerHTML = marked.parse(content); // 使用Markdown解析库
            hljs.highlightElement(div); // 启用代码高亮

            log.appendChild(div);
            log.scrollTop = log.scrollHeight;
        }

        function updateLastMessage(role, content) {
            const messages = document.querySelectorAll('.message');
            const last = messages[messages.length - 1];
            if (last.classList.contains(role)) {
                last.textContent = content;
            } else {
                appendMessage(role, content);
            }
            log.scrollTop = log.scrollHeight;
        }
    </script>
</body>

</html>